<template>
    <div class="chatList">
        <!-- 标题 -->
        <div class="listHeader">
            <!-- 标题插槽 -->
            <slot name="headerTitle"></slot>
            <!-- 搜索框 -->
            <div class="searchBox">
                <div class="search">
                    <span class="searchIconfont iconfont icon-likesprogramchaxun"></span>
                    <input type="text" placeholder="搜索对话" v-model="searchInputValue" @input="searchPrompt(searchInputValue)"/>
                    <span class="clearButton iconfont icon-likesprogramcuowu" :style="(searchInputValue.length > 0 ) ? { display: 'flex' } : {}" @click="clearSearch"></span>
                </div>
                <div class="addChat" @click="addChat();">
                    <span class="iconfont icon-likesprogramplus"></span>
                </div>
            </div>
        </div>
        <div class="chatListBox">
            <div v-for="(item, index) in props.chatList" class="chatItem" :class="isSelectChat(item) ? 'select' : ''" @click="selectChat(item);" :key="index">
                <div class="avatar" v-if="item.avatar">
                    <img :src="item.avatar" alt="" />
                </div>
                <div class="chatTitleAndNewMessageBox">
                    <div class="chatTitleBox">
                        <div class="title">{{ ChatViewApi.getChatTitle(item.title) }}</div>
                        <div class="time">{{ ChatViewApi.formatTimestamp(item.time, false) }}</div>
                    </div>
                    <div class="chatNewMessageBox">
                        <div class="newMessage">{{ item.content && item.content.length > 0 ? item.content : "暂无任何聊天记录" }}</div>
                        <div class="newMessageSize" v-if="item.newMessageSize > 0">{{ handleNewMessageSize(item.newMessageSize) }}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
export default defineComponent({
    name: 'chatList',
});

// 聊天
export interface Chat {
    title?: string;
    avatar?: string;
    content?: string;
    time?: number;
    newMessageSize?: number;
    sessionId?: string;
}

export const ChatViewApi = {
    getChatTitle (title: string): string {
        if (title && title.length > 0) {
            return title;
        } else {
            return "新建会话";
        }
    },
    timestampToDateTime (timestamp: number): string {
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份补零
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    formatTimestamp(timestamp: number, detailed: boolean = false): string {
        const date = new Date(timestamp);
        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        const yesterday = new Date(today);
        yesterday.setDate(yesterday.getDate() - 1);
        const lastWeek = new Date(today);
        lastWeek.setDate(lastWeek.getDate() - 2);

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        const dayOfWeek = weekDays[date.getDay()];

        const timePart = `${hours}:${minutes}`;
        const fullDatePart = `${year}-${month}-${day}`;
        const fullDateTime = `${fullDatePart} ${timePart}`;

        // 判断是否为今天
        if (date >= today) {
            return timePart; // 今天始终只显示时间
        }
        // 判断是否为昨天
        else if (date >= yesterday) {
            return detailed ? `昨天 ${timePart}` : '昨天';
        }
        // 判断是否在过去7天内
        else if (date >= lastWeek) {
            return detailed ? `${dayOfWeek} ${timePart}` : dayOfWeek;
        }
        // 其他情况
        else {
            return detailed ? fullDateTime : fullDatePart;
        }
    }
}

</script>
<script setup lang="ts">
    const props = withDefaults(defineProps<{
        chatList?: Chat[]; // 聊天列表
    }>(), {
        chatList: () => []
    });
    
    // 定义事件
    const emit = defineEmits<{
        // 删除事件
        (e: 'select',sessionId: string): void;
        (e: 'addChat'): void;
    }>();

    // 当前聊天
    const thisChat = ref(null);
    
    // 搜索框
    const searchInputValue = ref("");
    const searchPrompt = (value: string) => {
        console.log(value);
    };
    const clearSearch = () => {
        searchInputValue.value = '';
        console.log("搜索已清空");
    };

    // 处理未读消息数量
    const handleNewMessageSize = (size: number): string => {
        if (size > 99) {
            return "99+";
        } else {
            return size.toString();
        }
    };

    // 选择聊天
    const selectChat = (chat: Chat) => {
        thisChat.value = chat;
        emit("select", chat.sessionId);
    };

    // 判断是否选择
    const isSelectChat = (chat: Chat): boolean => {
        if (thisChat.value) {
            return thisChat.value.sessionId === chat.sessionId;
        }
        return false;
    };

    // 添加聊天
    const addChat = () => {
        emit("addChat");
    };

    // 监听聊天列表改变
    watch(() => props.chatList, () => {
        console.log("聊天列表改变");
        // 按照时间顺序，从新到旧排序
        props.chatList.sort((a, b) => {
            if (a.time && b.time) {
                return b.time - a.time;
            } else {
                return 0;
            }
        });
    }, { immediate: true, deep: true });

    // 暴露方法
    defineExpose({
        selectChat,
    });

</script>


<style src="@/assets/icons/iconfont.css" scoped></style>
<style scoped>
/* 聊天列表 */
.chatList {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}
/* 聊天列表标题 */
.chatList .listHeader {
    width: 100%;
    min-height: 70px;
    padding: 5px 10px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
}

/* 搜索框和添加按钮 */
.chatList .listHeader .searchBox {
    height: 35px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    position: relative;
}
/* 搜索框 */
.chatList .listHeader .searchBox .search {
    flex: 1;
    height: 30px;
    border-radius: 5px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid rgba(65, 185, 255, 0);
    background-color: rgba(255, 255, 255, .5);
    backdrop-filter: blur(2rem);
    -webkit-backdrop-filter: blur(2rem);
    -moz-backdrop-filter: blur(2rem);
    -ms-backdrop-filter: blur(2rem);
}
.chatList .listHeader .searchBox .search:focus-within {
    border: 1px solid rgba(65, 185, 255, 1);
    background-color: rgba(255, 255, 255, 1);
}
.chatList .listHeader .searchBox .search input {
    width: 100%;
    border: none;
    height: 100%;
    font-size: 14px;
    background-color: rgba(100, 100, 100, 0);
}
.chatList .listHeader .searchBox .search input:focus {
    outline: none;
}
.chatList .listHeader .searchBox .search .searchIconfont,
.chatList .listHeader .searchBox .search .clearButton {
    width: 30px;
    height: 30px;
    min-width: 30px;
    min-height: 30px;
    font-size: 16px;
    color: rgba(100, 100, 100, 1);
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all .3s;
}
.chatList .listHeader .searchBox .search .clearButton {
    display: none;
}
.chatList .listHeader .searchBox .search:focus-within .clearButton {
    display: flex;
}
.chatList .listHeader .searchBox .search .clearButton:hover {
    color: rgba(255, 0, 0, 1);
}
.chatList .listHeader .searchBox .search .clearButton:active {
    color: rgba(255, 0, 0, .5);
    transition: all .1s;
}

/* 添加对话按钮 */
.chatList .listHeader .searchBox .addChat {
    flex-shrink: 0;
    margin-left: 10px;
    width: 30px;
    height: 30x;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
    color: rgba(255, 255, 255, 1);
    background-color: rgba(65, 185, 255, 1);
    transition: all .3s;
}
.chatList .listHeader .searchBox .addChat:hover {
    background-color: rgba(65, 185, 255, .7);
}
.chatList .listHeader .searchBox .addChat:active {
    background-color: rgba(65, 185, 255, 1);
    transition: all .1s;
}

/* 消息列表 */
.chatList .chatListBox {
    width: 100%;
    flex: 1;
    overflow-y: auto;
}
/* 聊天列表项 */
.chatList .chatItem {
    width: 100%;
    height: 70px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 15px;
    overflow: hidden;
    transition: all .3s;
}
.chatList .chatItem.select {
    background-color: rgba(200, 200, 255, .2);
    color: rgba(65, 185, 255, 1);
}
.chatList .chatItem:hover {
    background-color: rgba(200, 200, 255, .2);
    color: rgba(65, 185, 255, 1);
}
.chatList .chatItem:active {
    background-color: rgba(200, 200, 255, .3);
    transition: all .1s;
}
/* 头像 */
.chatList .chatItem .avatar {
    width: 40px;
    min-width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
    border: 2px solid rgba(65, 185, 255, 1);
    overflow: hidden;
}
.chatList .chatItem .avatar img {
    width: 100%;
    height: 100%;
}
/* 标题信息和新消息 */
.chatList .chatItem .chatTitleAndNewMessageBox {
    width: 100%;
    height: 45px;
    font-size: 14px;
    overflow: hidden;
}
/* 标题 */
.chatList .chatItem .chatTitleAndNewMessageBox .chatTitleBox {
    width: 100%;
    height: 50%;
    display: flex;
    align-items: center;
    gap: 10px;
    overflow: hidden;
}
.chatList .chatItem .chatTitleAndNewMessageBox .chatTitleBox .title {
    flex: 1;
    /* 溢出省略号 */
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.chatList .chatItem .chatTitleAndNewMessageBox .chatTitleBox .time {
    flex-shrink: 0;
    height: 100%;
    font-size: 12px;
    color: rgba(0, 0, 0, .5);
    display: flex;
    align-items: center;
    overflow: hidden;
}
/* 新消息 */
.chatList .chatItem .chatTitleAndNewMessageBox .chatNewMessageBox {
    width: 100%;
    height: 50%;
    font-size: 12px;
    display: flex;
    align-items: center;
    gap: 10px;
    overflow: hidden;
}
.chatList .chatItem .chatTitleAndNewMessageBox .chatNewMessageBox .newMessage {
    flex: 1;
    height: 100%;
    color: rgba(0, 0, 0, .5);
    /* 溢出省略号 */
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.chatList .chatItem .chatTitleAndNewMessageBox .chatNewMessageBox .newMessageSize {
    flex-shrink: 0;
    padding: 0px 6px;
    height: 18px;
    font-size: 12px;
    font-weight: bold;
    border-radius: 18px;
    background-color: rgba(255, 0, 0, 1);
    color: rgba(255, 255, 255, 1);
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
}
</style>